package com.sudo.demo.security.handler;

import com.demo.common.base.pojo.JsonRes;
import com.google.gson.Gson;
import com.sudo.demo.security.util.GsonUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/9/20 14:55
 * @Description: 自定义认证拦截器
 * @desc AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        JsonRes<String> jsonRes = JsonRes.errorMsg(authException.getMessage());
        String json = GsonUtil.simpleObjToJson(jsonRes);
        response.getWriter().write(json);
    }

}